#define GPIO_Trig 7
#define GPIO_Echo 8
int hcsr_gpio_init(void)
{
    IoTGpioInit(GPIO_Trig);
    hi_io_set_func(GPIO_Trig, 0);   //0是普通IO口的意思
    IoTGpioSetDir(GPIO_Trig, IOT_GPIO_DIR_OUT);
    IoTGpioInit(GPIO_Echo);
    hi_io_set_func(GPIO_Echo, 0);
    IoTGpioSetDir(GPIO_Echo, IOT_GPIO_DIR_IN);
}

float GetDistance(void)
{
    IotGpioValue value = IOT_GPIO_VALUE0;
    float distance = 0.0;
    int flag = 0;
    static unsigned long start_time = 0, time = 0;
//发送声波
    IoTGpioSetOutputVal(GPIO_Trig, IOT_GPIO_VALUE1);
    hi_udelay(20);
    IoTGpioSetOutputVal(GPIO_Trig, IOT_GPIO_VALUE0);
    while (1)
    {//不断检测声波
        IoTGpioGetInputVal(GPIO_Echo, &value);
        //记录下高电平持续时间
        if (value == IOT_GPIO_VALUE1 && flag == 0)
        {
            start_time = hi_get_us();
            flag = 1;
        }
        if (value == IOT_GPIO_VALUE0 && flag == 1)
        {
            time = hi_get_us() - start_time;
            start_time = 0;
            break;
        }
    }
    distance = time * 0.034 / 2;
    printf("distance is %f\r\n", distance);
    return distance;
}
float AveDistance()
{
    float distance_sum[5];
    float distance = 0;
    //获取数据
    for (int i = 0; i < 5; i++)
    {
        distance_sum[i] = GetDistance();
    }
    int max_id = 0;
    int min_id = 0;
    //记录最大最小的数组下标
    for (int i = 1; i < 5; i++)
    {
        if (distance_sum[i] > distance_sum[max_id])
        {
            max_id = i;
        }
        if (distance_sum[i] < distance_sum[min_id])
        {
            min_id = i;
        }
    }
    for (int i = 0; i < 5; i++)
    {
        if (i != max_id && i != min_id)
        {
            distance += distance_sum[i];
        }
    }
    distance /= 3.0;
    return distance;
}